const DB = require("../config/Sequelize");
const BackCode = require("../utils/BackCode");
const CodeEnum = require("../utils/CodeEnum");
const RandomTool = require("../utils/RandomTool");
const redisConfig = require('../config/RedisConfig')
const SecretTool = require('../utils/SecretTool')

const UserService = {
    register: async (phone, code) => {
        console.log(55);

        const existPhone = await DB.Account.findAll({ where: { phone } });
        if (existPhone.length > 0) {
            return BackCode.buildResult(CodeEnum.ACCOUNT_REPEAT);
        }
        if (await redisConfig.exists(`register:code:${phone}`)) {
            let d = await redisConfig.get(`register:code:${phone}`)
            console.log('d: ', d.split('_'));
            const codeRes = (await redisConfig.get(`register:code:${phone}`)).split('_')[1]
            if (code !== codeRes) {
                return BackCode.buildError({ msg: '验证码错误' })
            }
        } else {
            return BackCode.buildError({ msg: '请先获取短信验证码' })
        }
        console.log(55);
        const name = RandomTool.randomName()
        const headImg = RandomTool.randomAvatar()

        // 生成随机的token
        const uesr = { name, headImg, phone }
        const token = SecretTool.jwtSign(uesr, '168h')

        await DB.Account.create({ username: name, head_img: headImg, phone });
        return BackCode.buildSuccessAndData({ data: `Bearer ${token}` });
    },
    login: async (phone, code, passward) => {
        console.log('code: ', code);
        console.log('phone: ', phone);
        if (!(phone && (code || passward))) return BackCode.buildSuccessAndMsg({ msg: '缺少必要参数' })
        let userInfo = await DB.Account.findAll({ where: { phone }, raw: true })
        if (userInfo.length === 0) return BackCode.buildResult(CodeEnum.ACCOUNT_UNREGISTER)
        if (passward) {
            if (!(SecretTool.md5(passward) === userInfo[0].pwd)) {
                return BackCode.buildResult(CodeEnum.ACCOUNT_PWD_ERROR)
            }
        } else {
            const exists = await redisConfig.exists(`login:code:${phone}`)
            if (!exists) return BackCode.buildError({ msg: '请先获取手机验证码' })
            let codeRes = (await redisConfig.get(`login:code:${phone}`)).split('_')[1]
            if (!(code === codeRes)) BackCode.buildError({ msg: '手机验证码不正确' })
        }
        let user = { ...userInfo[0], pwd: '' }
        let token = SecretTool.jwtSign(user, '16800000h')
        return BackCode.buildSuccessAndData({ data: `Bearer ${token}` })
    },
    forget: async (phone, code, passward) => {
        const existsCode = redisConfig.exists(`change:code:${phone}`)
        if (!existsCode) return BackCode.buildError({ msg: '请先获取手机验证码' })
        let codeRes = (await redisConfig.get(`change:code:${phone}`)).split('_')[1]
        if (codeRes !== code) return BackCode.buildError({ msg: '手机验证码不正确' })
        let pwd = SecretTool.md5(passward)
        await DB.Account.update({ pwd }, { where: { phone: phone } })
        return BackCode.buildResult({ msg: '修改成功' })
    },
    detail: async (req) => {
        const token = req.headers.authorization.split(' ').pop()

        const userInfo = SecretTool.jwtVerify(token)
        console.log('userInfo: ', userInfo);
        let data = await DB.Account.findAll({ where: { id: userInfo.id }, raw: true })
        return BackCode.buildSuccessAndData({ data: { ...data, pwd: '' } })
    },
    duration_record: async (req) => {
        let { productId, episodeId, duration } = req.body;
        if (!(productId && episodeId && duration)) {
            return BackCode.buildError({ msg: '缺少必要参数' })
        }
        let token = req.headers.authorization.split(' ').pop()
        let userInfo = SecretTool.jwtVerify(token)
        // 查询是否该用户有上报过学习时长，有则更新，无则插入
        let isHas = await DB.DurationRecord.findOne({
            where: { account_id: userInfo.id, product_id: productId, episode_id: episodeId },
            raw: true
        })
        if (isHas) {
            duration = Number(duration) + Number(isHas.duration)
            await DB.DurationRecord.update(
                { duration },
                {
                    where:
                        { account_id: userInfo.id, product_id: productId, episode_id: episodeId }
                }
            )
            return BackCode.buildSuccess()
        } else {
             await DB,DurationRecord.create({
                account_id: userInfo.id,
                product_id: productId,
                episode_id: episodeId,
                duration
             })
             return BackCode.buildSuccess()
        }
    }
};
module.exports = UserService;
